package tests;

import processing.core.PApplet;
import processing.opengl.*;
import javax.media.opengl.GL;
import com.sun.opengl.util.BufferUtil;
import java.nio.FloatBuffer;
import java.util.Vector;

public class Gl_test extends PApplet{

	 
	PGraphicsOpenGL pgl;
	GL gl;
	int quadlength;
	int[] quad_vbo = new int[1];
	 
	public void setup() {
	 size(300,300,OPENGL);
	 pgl = (PGraphicsOpenGL) g;
	 gl = pgl.gl;
	 initVBO();
	}
	public void draw() {
	 pgl.beginGL();
	 gl.glEnableClientState(GL.GL_VERTEX_ARRAY);
	 gl.glBindBuffer( GL.GL_ARRAY_BUFFER, quad_vbo[0]);
	 gl.glVertexPointer(2,GL.GL_FLOAT,0,0);
	 gl.glDrawArrays( GL.GL_QUADS, 0, quadlength);
	 gl.glBindBuffer( GL.GL_ARRAY_BUFFER, 0);
	 gl.glDisableClientState(GL.GL_VERTEX_ARRAY);
	 pgl.endGL();
	}
	 
	void initVBO() {
	 Vector quadvbo = new Vector();
	 quadvbo.addElement( new ms_vector2(20,20));
	 quadvbo.addElement( new ms_vector2(200,20));
	 quadvbo.addElement( new ms_vector2(200,200));
	 quadvbo.addElement( new ms_vector2(20,200));
	 
	 quadlength = quadvbo.size();
	 if (quadlength > 0) {
	   pgl.beginGL();
	   gl.glGenBuffers( 1, quad_vbo, 0 );
	   gl.glBindBuffer( GL.GL_ARRAY_BUFFER, quad_vbo[0] );
	   gl.glBufferData( GL.GL_ARRAY_BUFFER, quadlength * 2 * BufferUtil.SIZEOF_FLOAT, ms_vector2_to_float_buffer( quadvbo ), GL.GL_STATIC_DRAW );
	   gl.glBindBuffer( GL.GL_ARRAY_BUFFER, 0);
	   pgl.endGL();
	   quadvbo = null;
	 }
	}
	 
	class ms_vector2
	{
	 float x, y;
	 
	 // constructor
	 ms_vector2()
	 {
	   this.x = 0;
	   this.y = 0;
	 }
	 
	 ms_vector2( float _x, float _y)
	 {
	   this.x = _x;
	   this.y = _y;
	 }
	}
	 
	// buffer converters
	FloatBuffer ms_vector2_to_float_buffer( Vector _vector )
	{
	 FloatBuffer a  = BufferUtil.newFloatBuffer( _vector.size() * 2 );      
	 
	 for( int i = 0; i < _vector.size(); i++ )
	 {
	   ms_vector2 v = (ms_vector2) _vector.elementAt( i );
	   a.put( v.x );
	   a.put( v.y );
	 }
	 a.rewind();
	 return a;
	}

}
